#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>

int fd;

void handler(int sig)
{
    char buf[50];
    snprintf(buf, 50, "[PID %d] Received SIGINT\n", getpid());
    write(fd, buf, strlen(buf));
}

int main()
{
    fd = open("sigfork.log", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    write(fd, "=== Parent-Child Signal Test ===\n", 34);

    signal(SIGINT, handler);
    pid_t pid = fork();

    if (pid == 0)
    {
        write(fd, "[CHILD] Process started\n", 24);
        execl("/bin/ls", "ls", "-l", NULL); // 执行后恢复默认信号处理
    }
    else
    {
        sleep(1);
        kill(pid, SIGINT); // 向子进程发送 SIGINT
        write(fd, "[PARENT] Signal sent to child\n", 30);
    }

    close(fd);
    return 0;
}